<?php
declare (strict_types = 1);

namespace app\command;

use app\weapp\library\WeAppApi;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\admin\model\HrField;
use app\admin\model\HrFieldType;
use app\admin\model\HrGroupList;

class SyncData extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('syncdata')
            ->setDescription('the syncdata command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('syncdata');
        $output->writeln('sync Department start');
        $this->syncDepartment();
        $output->writeln('sync Department end');
        $output->writeln('sync HrField start');
        $this->syncMember();
        $output->writeln('sync HrField end');
       
    }
    //同步部门
    protected function syncDepartment(){
        $api = new  WeAppApi(['agent_id'=>'1000007',
        'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE']);
        $result = $api->SyncGroup();
    }
    //同步Hr字段信息
    protected function syncMember(){
        $api = new  WeAppApi(['agent_id'=>'1000006',
        'secret' => 'vJLtbFBElziZAc0HFj8CPw_sL9nPAVfHSmMXUbNTphw']);
        $result = $api->SyncHrField();
        if($result !== false){
            foreach ($result as $key => $value) {
                $group = HrGroupList::getByGroupId($value['group_id']);
                if(empty($group)){
                    $group = HrGroupList::create(['group_id'=>$value['group_id'],'group_name'=>$value['group_name'],'field_list'=>$value['field_list']?json_encode($value['field_list']):'']);
                }else{
                    $group->group_id = $value['group_id'];
                    $group->group_name = $value['group_name'];
                    $group->field_list = $value['field_list']?json_encode($value['field_list']):'';
                    $group->save();
                }
                if(!empty($value['field_list'])){
                    foreach ($value['field_list'] as $k => $v) {
                    $field = HrField::getByFieldid($v['fieldid']);
                    if(empty($field)){
                            $field = HrField::create(['fieldid'=>$v['fieldid'],'field_name'=>$v['field_name'],'field_type'=>$v['field_type'],'is_must'=>(int)$v['is_must']]);
                        }else{
                            $field->fieldid = $v['fieldid'];
                            $field->field_name = $v['field_name'];
                            $field->field_list = json_encode($value['group_name']);
                            $field->field_type = $v['field_type'];
                            $field->is_must = (int)$v['is_must'];
                            $field->save();
                        }
                    }
                }
            }
        }
    }
}
